package com.htkj.questservice

import android.accessibilityservice.AccessibilityService
import android.accessibilityservice.AccessibilityServiceInfo
import android.annotation.SuppressLint
import android.app.ActivityManager
import android.app.usage.UsageStatsManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import android.text.TextUtils
import android.util.Log
import android.view.accessibility.AccessibilityManager
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity


class MainActivity : AppCompatActivity() {
    private var batteryMonitor: BatteryMonitor? = null

    private val mHandler by lazy {
        Handler(Looper.getMainLooper())
    }

    private val runnable = object : Runnable {
        override fun run() {
            // 执行查询逻辑（如网络请求、数据库读取等）
            queryData()
            // 循环调用自身
            mHandler.postDelayed(this,  1000)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
//        batteryMonitor = BatteryMonitor(
//            this
//        ) { percentage, isCharging ->
//            runOnUiThread {
//              Toast.makeText(this,"当前电量${percentage}%",0).show()
//                if (isCharging) {
//
//
//                }
//            }
//        }
//        batteryMonitor?.startMonitoring()
//        val foregroundApp = ForegroundAppDetector.getForegroundApp(this);
//        Toast.makeText(this,"当前电量${foregroundApp}%",0).show()
//
//        // 在Activity或Application中启动服务
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            startForegroundService(Intent(this, ForegroundAppMonitorService::class.java))
//        } else {
//            startService(Intent(this, ForegroundAppMonitorService::class.java))
//        }
//        if (isAccessibilityServiceEnabled())  {
//            // 服务已启用
//            Toast.makeText(this,"服务已开启",0).show();
//        } else {
//            // 跳转到辅助设置页面（用户需手动开启）
//            val intent = Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
//            startActivity(intent)
//        }
//        val intent: Intent = Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
//        startActivity(intent)

        val intent = Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS)
        startActivity(intent)


        mHandler.postDelayed(runnable,  1000)

    }

    override fun onDestroy() {
        super.onDestroy()
        batteryMonitor?.stopMonitoring()
    }

    override fun onStart() {
        super.onStart()
//        if (isMyAccessibilityServiceEnabled(this))  {
//            // 服务已启用
//            Toast.makeText(this,"服务已开启",0).show();
//        } else {
//            // 跳转到辅助设置页面（用户需手动开启）
//            val intent = Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
//            startActivity(intent)
//        }
    }

    //    // 获取前台应用
//    String foregroundApp = ForegroundAppDetector.getForegroundApp(this);
//    Log.d("ForegroundApp", "当前应用: " + foregroundApp);
//
//// 检查并请求权限（Android 5.0+）
//    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//        if (!ForegroundAppDetector.checkUsageStatsPermission(this))  {
//            new AlertDialog.Builder(this)
//                .setTitle("需要权限")
//                .setMessage("请开启「使用情况访问权限」以获取前台应用信息")
//                .setPositiveButton("去设置", (dialog, which) -> {
//                ForegroundAppDetector.requestUsageStatsPermission(this);
//            })
//            .show();
//        }
//    }
    fun queryData(){
        val usageStatsManager = getSystemService(Context.USAGE_STATS_SERVICE)  as UsageStatsManager
        val currentTime = System.currentTimeMillis()
        val stats = usageStatsManager.queryUsageStats(
            UsageStatsManager.INTERVAL_DAILY,
            currentTime - 1000*60, // 1分钟前
            currentTime
        )
        val foregroundApp = stats.maxByOrNull  { it.lastTimeUsed  }?.packageName
        if(!TextUtils.isEmpty(foregroundApp)){
            Toast.makeText(this,foregroundApp,0).show()
        }
        Log.e("CS","${foregroundApp}---${stats}--${getRunProcessName()}")
    }

    fun isMyAccessibilityServiceEnabled(context: Context): Boolean {
        Log.e("CS","isMyAccessibilityServiceEnabled")
        val serviceName = ComponentName(context, MyAccessibilityService::class.java).flattenToString()
        val am = context.getSystemService(Context.ACCESSIBILITY_SERVICE)  as AccessibilityManager
        val enabledServices = am.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_ALL_MASK)

        return enabledServices.any  {
            Log.e("CS","${it.id}------${serviceName}")
            it.id.contains("MyAccessibilityService")&& it.id.contains(packageName) }
    }

    fun getRunProcessName():String?{
        val am = getSystemService(Context.ACTIVITY_SERVICE)  as ActivityManager
        val runningProcesses = am.runningAppProcesses
        val foregroundProcess = runningProcesses.firstOrNull  { it.importance  == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND }
        return foregroundProcess?.processName
    }
}

